package tech.cn.note.excel;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.jxls.expression.JexlExpressionEvaluator;

/**
 * jxls填充占位符时，JexlExpressionEvaluator在catch到Exception后处理方式为
 * throw new EvaluationException("An error occurred when evaluating expression " + expression, e);
 * 错误日志会刷屏，为了避免刷屏，重写JexlExpressionEvaluator的异常处理
 */
@Slf4j
public class CustomJexlExpressionEvaluator extends JexlExpressionEvaluator {
    private static final ThreadLocal<Map<String, JexlExpression>> expressionMapThreadLocal = ThreadLocal.withInitial(HashMap::new);

    @Override
    public Object evaluate(String expression, Map<String, Object> context) {
        JexlContext jexlContext = new MapContext(context);
        try {
            Map<String, JexlExpression> expressionMap = expressionMapThreadLocal.get();
            JexlExpression jexlExpression = expressionMap.get(expression);
            if (jexlExpression == null) {
                jexlExpression = getJexlEngine().createExpression(expression);
                expressionMap.put(expression, jexlExpression);
            }
            return jexlExpression.evaluate(jexlContext);
        } catch (Exception e) {
            log.warn("An error occurred when evaluating expression[{}]：{}", expression, e.getMessage());
            return null;
        }
    }

}
